package service

import (
	"errors"
	"fmt"
	"im/model"
	"im/util"
	"math/rand"
	"time"
)

type UserService struct{

}
func (s *UserService)Register(mobile,plainpwd,nickname,avatar,sex string)(user model.User,err error){
	//查询手机号是否存在
	tmp:=model.User{}
	_,err =DbEngine.Where("mobile=?",mobile).Get(&tmp)
	if err!=nil {
		return tmp,err
	}
	//已存在者提示
	if tmp.Id>0 {
		return tmp,errors.New("该手机号已存在")
	}
	//不存在则插入数据库
	tmp.Avatar=avatar
	tmp.Mobile=mobile
	tmp.Sex=sex
	tmp.Create=time.Now()
	salt:=fmt.Sprintf("%06d",rand.Int63n(10000))
	tmp.Salt=salt
	tmp.Password=util.MakePasswd(plainpwd,salt)
	tmp.Token=fmt.Sprintf("%08d",rand.Int31())
	_,err=DbEngine.InsertOne(&tmp)
	return tmp,err
}
func (s *UserService)Login(mobile,plainpwd string)(user model.User,err error){
	tmp:=model.User{}
	DbEngine.Where("mobile=?",mobile).Get(&tmp)
	if tmp.Id==0{
		return tmp,errors.New("账号不存在")
	}
	if !util.ValidatePasswd(plainpwd, tmp.Salt,  tmp.Password){
		return tmp,errors.New("密码不正确")
	}
	str:=fmt.Sprintf("%d",time.Now().Unix())
	token:=util.Md5Encode(str)
	tmp.Token=token
	DbEngine.Id(tmp.Id).Cols("token",token).Update(&tmp)
	return tmp,nil
}
